import FileApi from '../../api/file'
import CategoryApi from '../../api/category'
import AchieveApi from '../../api/achieve'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    fileList: [], // 选择文件的数组
    file: [], // 发起请求时需要用到这个数组
    values: ['1312', '1231231'],
    propertyValueList: [],
    stepActive: 0,
    columns: [{
      values: ["国际级", "国家级", "省级", "市级", "校级", "院级"]
    },
    {
      values: ['特等奖', '一等奖', '二等奖', '三等奖', '优秀奖', '金牌', '银牌', '铜牌']
    }
    ],
    categoryInfo: {},
    properties: [],
    steps: [{
      text: '成果基本信息',
    },
    {
      text: '成果属性',
    },
    {
      text: '证明材料',
    },
    ],
    //成果基本信息
    achieveName: '',
    uploader: '',
    number: '',
    getTime: '',
    achieveId: '',

    currentDate: new Date().getTime(),
    maxDate: new Date().getTime(),
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      }
      if (type === 'month') {
        return `${value}月`;
      }
      return value;
    },
    cDate: '',
    show: false,
    level: '', // 级别 国家级等等
    rank: '', // 排名
    showLevel: false, // 显示级别
    showRank: false, // 显示等级,
  },
  showPopup() {
    this.setData({
      show: true
    });
  },
  showPopupLevel() {
    this.setData({
      showLevel: true
    });
  },

  onClose() {
    this.setData({
      show: false,
      showLevel: false,
      showRank: false
    });
  },
  confirmTime() {
    this.setData({
      show: false,
    })
    var date = new Date(this.data.currentDate)

    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    this.setData({
      cDate: Y + M + D
    })
  },
  confirmLevelRank(event) {
    this.setData({
      level: event.detail.value[0],
      rank: event.detail.value[1],
      showLevel: false
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.on('acceptDataFromOpenerPage', function (data) {
      that.setData({
        categoryInfo: data.data
      })
    })
    this.getCategoryProperties(this.data.categoryInfo.id)
  },
  getCategoryProperties(id) {
    var that = this
    CategoryApi.getCategoryProperties(id).then(res => {
      let propertyValueList = []
      for (let index = 0; index < res.data.data.properties.length; index++) {
        var propertyValue = {
          propertyId: res.data.data.properties[index].id,
          propertyName: res.data.data.properties[index].propertyName,
          propertyValue: '',
          achieveId: res.data.data.achieveId,
          ename: res.data.data.properties[index].ename,
          must: res.data.data.properties[index].must,
        }
        propertyValueList.push(propertyValue)
      }
      that.setData({
        properties: res.data.data.properties,
        propertyValueList: propertyValueList,
      })
    })
  },
  onInput(event) {
    this.setData({
      currentDate: event.detail,
    });
  },

  nextStep() {
    if (this.data.stepActive == 0) {
      // 成果基本信息必须传成果名称和获奖时间
      if (this.data.cDate === '' || this.data.achieveName === '') {
        wx.showToast({
          title: "带星号的为必填项",
          icon: "none"
        })
        return
      }
    }
    this.setData({
      stepActive: this.data.stepActive + 1
    })
  },
  previousStep() {
    if (this.data.stepActive == 0) {
      wx.showToast({
        title: '已经是第一步了',
        icon: 'none'
      })
    } else {
      this.setData({
        stepActive: this.data.stepActive - 1
      })
    }
  },
  // 成果属性失去焦点
  blurInput(e) {
    let index = e.currentTarget.dataset.index
    this.data.propertyValueList[index].propertyValue = e.detail.value
  },
  beforeRead(event) {
    const {
      file,
      callback
    } = event.detail;
    var suffix = file.name.substring(file.name.lastIndexOf(".") + 1)
    if (file.type != 'image' && suffix != 'pdf') {
      wx.showToast({
        title: '请上传图片或pdf',
        icon: 'none',
        mask: false
      })
    } else {
      callback(file.type === 'image' || file.type === 'file');
    }
  },
  afterRead(event) {
    this.setData({
      fileList: this.data.fileList.concat(event.detail.file)
    })
  },
  deleteFile(event) {
    const index = event.detail.index
    this.data.fileList.splice(index, 1)
    this.setData({
      fileList: this.data.fileList
    })
  },
  GenNonDuplicateID(randomLength){
    return Number(Math.random().toString().substr(0,randomLength) + Date.now()).toString(36)
  },
  // 点击完成上传按钮的事件

  gotoUpload() {
    wx.showLoading({
      title: '正在上传...',
    })
    var that = this
    if (that.data.achieveId === undefined ||
      that.data.achieveId === null ||
      that.data.achieveId === "") {
      that.setData({
        achieveId: that.GenNonDuplicateID(10)
      })
    }
    // 先上传文件
    wx.uploadFile({
      filePath: this.data.fileList[0].url,
      name: 'file',
      url: 'http://127.0.0.1:8090/file/uploadFile',
      // url: 'http://116.204.108.230:8090/file/uploadFile',
      header: { "Content-Type": "multipart/form-data", "Authentication": wx.getStorageSync('token') },
      formData: {
        achieveId: that.data.achieveId,
        fileName: that.data.fileList[0].name,
      },
      success(res) {
        var fileRes = {}
        fileRes = JSON.parse(res.data)
        if (fileRes.code === 200) {
          // 准备上传的数据
          // 1. achieve
          var achieve = {
            id: that.data.achieveId,
            categoryId: that.data.categoryInfo.id,
            getTime: that.data.cDate,
            achieveName: that.data.achieveName,
            level: that.data.level + that.data.rank
          }
          // 2. files
          var files = [fileRes.data[0]]
          // 3. propertyValueList
          for (let index = 0; index < that.data.propertyValueList.length; index++) {
            that.data.propertyValueList[index].achieveId = that.data.achieveId
          }
          var propertyValueList = that.data.propertyValueList
          var achieveVo = {
            achieve,
            files,
            propertyValueList,
          }
          // 数据准备完成，开始上传吧
          AchieveApi.uploadAchieve(achieveVo).then(res => {
            if (res.data.code === 200) {
              wx.showToast({
                title: '上传成功',
                icon: 'success'
              })
              wx.hideLoading({
                success: (res) => {
                  setTimeout(() => {
                    wx.switchTab({
                      url: '../index/index',
                    })
                  }, 500);
                },
              })
            } else {
              return wx.showToast({
                title: res.data.data,
                icon: 'none'
              })
            }
          })
        } else {
          return wx.showToast({
            title: res.data.data,
            icon: "none"
          })
        }
      }
    })
  },
})
